package cn.itcast.bos.web.action;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.User;
import cn.itcast.bos.utils.BosGetSesstionUser;
import cn.itcast.bos.utils.MD5Utils;
import cn.itcast.bos.web.action.base.BaseAction;

@Controller
@Scope(value="prototype")
public class UserAction extends BaseAction<User>{
	//验证码 验证
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	public String login(){
		String validatesCode = (String) ServletActionContext.getRequest().getSession().getAttribute("key");
		if (StringUtils.isBlank(checkcode) || !checkcode.equals(validatesCode)) {
			this.addActionError(this.getText("validatesCodeError"));
			return "login";
		}else {
			// 登录成功 验证用户信息
			/*User user=userService.login(model);
			if (user !=null) {
				ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
				return "index";
			}else {
				this.addActionError(this.getText("loginFailError"));
				return "login";
			}*/
			Subject subject = SecurityUtils.getSubject();
			String username = model.getUsername();
			String password = model.getPassword();
			password = MD5Utils.md5(password);
			//UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			AuthenticationToken token = new UsernamePasswordToken(username, password);
			try {
				subject.login(token);
				User user = (User) subject.getPrincipal();
				//登录成功将user 放入session 到系统首页
				ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
				
			} catch (UnknownAccountException e) {
				e.printStackTrace();
				this.addActionError("用户不存在");
				return "login";
			}catch (IncorrectCredentialsException e) {
				e.printStackTrace();
				this.addActionError("密码错误");
				return "login";
			}
			return "index";
		}
	}
	
	//退出logOut
	public String logOut(){
		ServletActionContext.getRequest().getSession().invalidate();
		return "login";
	}
	
	//editPassword修改 密码
	public String editPassword() throws IOException{
		String password = model.getPassword();
		String id = BosGetSesstionUser.getBosLoginUser().getId();
		String s="1";
		try {
			userService.editPassword(id,password);
		} catch (Exception e) {
			e.printStackTrace();
			s="2";
		}
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(s);
		return NONE;
	}
}
